/*
 * @Autor: lh
 * @Date: 2023-08-21 09:50:00
 * @LastEditors: lh
 * @LastEditTime: 2024-03-04 17:32:46
 * @Description:
 */
import { ref } from "vue"
import store from "@/store"
import { defineStore } from "pinia"
import { usePermissionStore } from "./permission"
import { useTagsViewStore } from "./tags-view"
import { useSettingsStore } from "./settings"
import { getToken, removeToken, setToken } from "@/utils/cache/cookies"
import router, { resetRouter } from "@/router"
import { loginApi, getUserInfoApi, selectAllSysUser } from "@/api/login"
import { type LoginRequestData } from "@/api/login/types/login"
import { type RouteRecordRaw } from "vue-router"
import routeSettings from "@/config/route"

export const useUserStore = defineStore("user", () => {
  const token = ref<string>(getToken() || "")
  const roles = ref<string[]>([])
  const username = ref<string>("")
  const rolesName = ref<string>("")
  const headImg = ref<string>("") // 用户头像
  const personnelList = ref<any>([]) // 人员列表
  const userId = ref<number>() // 用户id
  const account = ref<string>("") // 账号
  const gender = ref<number>(0) // 性别

  const permissionStore = usePermissionStore()
  const tagsViewStore = useTagsViewStore()
  const settingsStore = useSettingsStore()

  /** 设置角色数组 */
  const setRoles = (value: string[]) => {
    roles.value = value
  }
  /** 登录 */
  const login = async ({ userName, loginPass, code }: LoginRequestData) => {
    const { data } = await loginApi({ userName, loginPass, code })
    // debugger;
    console.log(data)

    setToken(data.token)
    localStorage.setItem("userinfo", JSON.stringify(data))
    token.value = data.token
  }
  /** 获取用户详情 */
  const getInfo = async () => {
    const data: any = JSON.parse(localStorage.getItem("userinfo") || "{}") //await getUserInfoApi()
    data["roles"] = ["admin"]
    username.value = data.name
    userId.value = data.id
    rolesName.value = data.roleName
    headImg.value = data.image
    account.value = data.userName
    gender.value = data.gender
    // 验证返回的 roles 是否为一个非空数组，否则塞入一个没有任何作用的默认角色，防止路由守卫逻辑进入无限循环
    roles.value = data.roles?.length > 0 ? data.roles : routeSettings.defaultRoles
    let plist = await getPersonnelFn()
    if (plist.code == 200) {
      personnelList.value = plist.data
    }
    // console.log(plist,'--plist--');
  }
  /** 获取查询所有系统用户用户--按照角色分级 */
  const getPersonnelFn = () => {
    return selectAllSysUser()
  }
  /** 切换角色 */
  const changeRoles = async (role: string) => {
    const newToken = "token-" + role
    token.value = newToken
    setToken(newToken)
    await getInfo()
    console.log(roles.value, "---roles.value")
    permissionStore.setRoutes(roles.value)
    resetRouter()
    console.log(permissionStore.dynamicRoutes, "permissionStore.dynamicRoutes--")

    permissionStore.dynamicRoutes.forEach((item: RouteRecordRaw) => {
      router.addRoute(item)
    })
    _resetTagsView()
  }
  /** 登出 */
  const logout = () => {
    removeToken()
    token.value = ""
    roles.value = []
    resetRouter()
    _resetTagsView()
  }
  /** 重置 Token */
  const resetToken = () => {
    removeToken()
    token.value = ""
    roles.value = []
  }
  /** 重置 Visited Views 和 Cached Views */
  const _resetTagsView = () => {
    if (!settingsStore.cacheTagsView) {
      tagsViewStore.delAllVisitedViews()
      tagsViewStore.delAllCachedViews()
    }
  }

  return {
    token,
    roles,
    username,
    userId,
    rolesName,
    personnelList,
    setRoles,
    login,
    getInfo,
    changeRoles,
    logout,
    resetToken,
    headImg,
    account,
    gender
  }
})

/** 在 setup 外使用 */
export function useUserStoreHook() {
  return useUserStore(store)
}
